/*
 * @lc app=leetcode.cn id=1670 lang=javascript
 *
 * [1670] 设计前中后队列
 */

// @lc code=start
function NodeList (val, next = null) {
    this.val = val;
    this.next = next;
}
var FrontMiddleBackQueue = function() {
  this.head = new NodeList(-1);
};

/** 
 * @param {number} val
 * @return {void}
 */
FrontMiddleBackQueue.prototype.pushFront = function(val) {
    this.head.next = new NodeList(val, this.head.next);
}

/** 
 * @param {number} val
 * @return {void}
 */
FrontMiddleBackQueue.prototype.pushMiddle = function(val) {
  let slot = this.head;
  let fast = this.head.next;
  while(fast?.next) {
      fast = fast.next.next;
      slot = slot.next;
  }
  const middle = slot.next;
  slot.next = new NodeList(val, middle);
};

/** 
 * @param {number} val
 * @return {void}
 */
FrontMiddleBackQueue.prototype.pushBack = function(val) {
  let node = this.head;
  while(node.next) {
      node = node.next;
  }
  node.next = new NodeList(val);
};

/**
 * @return {number}
 */
FrontMiddleBackQueue.prototype.popFront = function() {
   let front = this.head.next;
   if (!front) return -1;
   this.head.next = front.next;
   return front.val;
};

/**
 * @return {number}
 */
FrontMiddleBackQueue.prototype.popMiddle = function() {
  let slot = this.head;
  let fast = this.head.next;
  if (!fast) return -1;
  while(fast?.next) {
      fast = fast.next.next;
      if (fast) {
          slot = slot.next;
      }
  }
  const middle = slot.next;
  slot.next = middle.next;
  return middle.val;
};

/**
 * @return {number}
 */
FrontMiddleBackQueue.prototype.popBack = function() {
  let back = this.head;
  if (!back.next) return -1;
  while(back?.next?.next) {
      back = back.next;
  }
  const val = back.next.val;
  back.next = null;
  return val;
};

/**
 * Your FrontMiddleBackQueue object will be instantiated and called as such:
 * var obj = new FrontMiddleBackQueue()
 * obj.pushFront(val)
 * obj.pushMiddle(val)
 * obj.pushBack(val)
 * var param_4 = obj.popFront()
 * var param_5 = obj.popMiddle()
 * var param_6 = obj.popBack()
 */
// @lc code=end

